package com.apes.fn.controlling.vehicle.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.crm.vip.vipInfo.VipInfo;
import com.apes.crm.vip.vipInfo.VipInfoRepository;
import com.apes.fn.controlling.vehicle.model.VehicleInfo;
import com.apes.fn.controlling.vehicle.model.VehicleInfoCombine;
import com.apes.fn.controlling.vehicle.repository.VehicleInfoCombineRepository;
import com.apes.fn.controlling.vehicle.repository.VehicleInfoRepository;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.crm.customerExpand.FnCustomerExpandRepository;
import com.apes.fn.server.pickUpCar.model.PickUpCar;
import com.apes.fn.server.pickUpCar.repository.PickUpCarRepository;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.server.servicePlan.service.ServicePlanceService;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.query.SqlService;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyIdentification;
import com.apes.scm.masterdata.party.model.Person;
import com.apes.scm.masterdata.party.repository.PartyIdentificationRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.party.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Creator: zouyc
 * CreateDate: 2021-03-22 14:15
 * Description:
 **/
@Service("vehicleInfoForCombine")
public class VehicleInfoForCombineService extends DomainService {

    @Autowired
    PickUpCarRepository pickUpCarRepository;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    FnCustomerExpandRepository fnCustomerExpandRepository;
    @Autowired
    PartyIdentificationRepository partyIdentificationRepository;
    @Autowired
    VipInfoRepository vipInfoRepository;
    @Autowired
    SqlService sqlService;
    @Autowired
    ServicePlanRepository servicePlanRepository;

    //基于构造方法，注入
    private final VehicleInfoRepository repository;
    private final VehicleInfoCombineRepository vehicleInfoCombineRepository;
    public VehicleInfoForCombineService(VehicleInfoRepository repository,VehicleInfoCombineRepository vehicleInfoCombineRepository) {
        this.repository = repository;
        this.vehicleInfoCombineRepository = vehicleInfoCombineRepository;
    }

    /**
     * 符合模型数据从多个模型来，只要每次触发了更改，就默认数据重取：
     * 每次都直接构建一个新的模型，设置id（就不用初始化了。）
     * @param VehicleInfo
     */
    @OutboxSubscriber(id="vehicleInfoForCombine.state.vehicleInfo", name="车辆总控整合表")
    public void listenVehicleInfo(VehicleInfo VehicleInfo){
        Dept belongDept = VehicleInfo.getDept();
        FnCustomerExpand fnCustomerExpand = VehicleInfo.getFnCustomerExpand();

        VehicleInfoCombine vehicleInfoCombine = new VehicleInfoCombine();
        vehicleInfoCombine.setId(VehicleInfo.getId());
        vehicleInfoCombine.setPickCarId(VehicleInfo.getPickUpCar());
        vehicleInfoCombine.setFnCustomerExpandId(fnCustomerExpand.getId());
        vehicleInfoCombine.setJekunCode(fnCustomerExpand.getJekunModelCode());
        vehicleInfoCombine.setDeptId(belongDept.getId());
        vehicleInfoCombine.setEnd("finish".equals(VehicleInfo.getState()) || "repeal".equals(VehicleInfo.getState()) ? true : false);
        //关于接车信息
        PickUpCar pickUpCar =
                pickUpCarRepository.findOne(Optional.ofNullable(vehicleInfoCombine.getPickCarId()).orElseGet(()->"nonData"));
        if(pickUpCar != null){
            vehicleInfoCombine.setPickCarTime(pickUpCar.getCreateDate());
            vehicleInfoCombine.setReturnCarTime(pickUpCar.getFinishDate());
            vehicleInfoCombine.setEstimateDate(pickUpCar.getEstimateDate());
            if (pickUpCar.getCreator()!=null){
                vehicleInfoCombine.setPickCarUId(pickUpCar.getCreator());
                vehicleInfoCombine.setPickCarUName(partyRoleRepository.findOne(pickUpCar.getCreator()).getName());
            }
        }
        //和车辆相关信息
        if (pickUpCar != null) {
            vehicleInfoCombine.setServeType((String) serviceType(fnCustomerExpand.getId(),pickUpCar.getCreateDate()).get("name"));
            vehicleInfoCombine.setServeTypeId((String) serviceType(fnCustomerExpand.getId(),pickUpCar.getCreateDate()).get("id"));
        }

        vehicleInfoCombine.setVipLevel(fnCustomerExpand.getCustomerLevelName());
        vehicleInfoCombine.setVipLevelId(fnCustomerExpand.getCustomerLevelId());
        if (fnCustomerExpand.getCustomerLivenessName()==null){
            JSONObject tempJson = new JSONObject();
            tempJson.put("carLicense",fnCustomerExpand.getCarLicense());
            tempJson.put("vendorCode",fnCustomerExpand.getVendorCode());
            JSONObject re = null ;
            try {
                re = new JSONObject(this.invoke("fn.customerCar.findOne", tempJson));
            } catch (Exception e) {
                return;
            }
            if (re.getJSONObject("customer")!=null){
                vehicleInfoCombine.setVipLiveness(re.getJSONObject("customer").getString("activityLabel"));
                vehicleInfoCombine.setVipLivenessId("空值".equals(re.getJSONObject("customer").getString("activityLabel")) ? "00":re.getJSONObject("customer").getString("activity"));
            }
        }else {
            vehicleInfoCombine.setVipLiveness(fnCustomerExpand.getCustomerLivenessName());
            vehicleInfoCombine.setVipLivenessId("空值".equals(fnCustomerExpand.getCustomerLivenessName()) ? "00":fnCustomerExpand.getCustomerLivenessId());
        }


        JSONObject carJson = obtainCarInfo(Optional.ofNullable(vehicleInfoCombine.getJekunCode()).orElseGet(()->""));
        vehicleInfoCombine.setCarLicense(fnCustomerExpand.getCarLicense());
        vehicleInfoCombine.setMobile(fnCustomerExpand.getMobile());
        vehicleInfoCombine.setBrandId(carJson.getString("BRAND_ID"));
        vehicleInfoCombine.setBrandName(carJson.getString("BRAND_NAME"));
        vehicleInfoCombine.setCarModelLabel(fnCustomerExpand.getCarModelLabel());
        //其他信息
        vehicleInfoCombine.setDeptName(belongDept.getName());
        JSONObject workPlatfrom = obtainWorkPlatfrom(fnCustomerExpand.getId(),belongDept.getId());
        vehicleInfoCombine.setWorkPlatform(workPlatfrom.getString("WORK_PLATFORM"));
        vehicleInfoCombine.setWorkPlatformName(distinctWorkPlat(workPlatfrom.getString("WORK_PLATFORM"),","));
        vehicleInfoCombineRepository.saveAndFlush(vehicleInfoCombine);
    }

    /**
     * 获取服务类型
     * @param fnCustomerExpand
     * @param fnPickUpCar
     * @return
     */
    public Map serviceType(String fnCustomerExpand ,Date fnPickUpCar){
        Map<String,String> map = new HashMap();
        List<ServicePlan> servicePlans = servicePlanRepository.findServerType(fnCustomerExpand, fnPickUpCar, "receivables");
        servicePlans.stream().forEach(servicePlan -> {
            servicePlan.getServicePlanItems().stream().forEach(servicePlanItem -> {
                if (servicePlanItem.getServeType()!=null){
                    map.put(servicePlanItem.getServeType().getId(),servicePlanItem.getServeType().getName());
                }
            });
        });
        StringBuffer valuesBF = new StringBuffer();
        StringBuffer keysBF = new StringBuffer();
        for (String value : map.values()) {
            valuesBF.append(value+",");
        }
        for (String key : map.keySet()) {
            keysBF.append(key+",");
        }

        if (!"".equals(valuesBF.toString()))valuesBF.deleteCharAt(valuesBF.length()-1);
        if (!"".equals(keysBF.toString()))keysBF.deleteCharAt(keysBF.length()-1);
        Map<String,String> re = new HashMap();
        re.put("name",valuesBF.toString());
        re.put("id",keysBF.toString());
        return re;
    }

    /**
     * 从frame json 转化为 阿里 json
     * @param json
     * @return
     */
    private static JSONObject tranType(com.apestech.framework.json.JSONObject json){
        return JSONObject.parseObject(JSON.toJSONString(json));
    }

    private static JSONArray tranTypeArray(com.apestech.framework.json.JSONArray array){
        return array.stream().map(item ->tranType((com.apestech.framework.json.JSONObject) item)).collect(Collectors.toCollection(JSONArray::new));
    }

    /**
     * 根据
     * @param
     * @return
     */
    private JSONObject obtainCarInfo(String jeKunCode){
        com.apestech.framework.json.JSONObject jsonObject = new com.apestech.framework.json.JSONObject();
        jsonObject.put("JEKUN_MODEL_CODE",jeKunCode);
        JSONArray array = tranTypeArray(sqlService.queryId("serverControl.qryBrand",jsonObject));
        return (JSONObject) Optional.ofNullable(array.stream().findFirst().orElse(null)).orElseGet(()->new JSONObject());
    }


    /**
     * 根据
     * @param
     * @return
     */
    private JSONObject obtainWorkPlatfrom(String fn_id,String dept_id){
        com.apestech.framework.json.JSONObject jsonObject = new com.apestech.framework.json.JSONObject();
        jsonObject.put("FN_ID",fn_id);
        jsonObject.put("DEPT_ID",dept_id);
        JSONArray array = tranTypeArray(sqlService.queryId("serverControl.qryWorkPlatform",jsonObject));
        return (JSONObject) Optional.ofNullable(array.stream().findFirst().orElse(null)).orElseGet(()->new JSONObject());
    }


    public String distinctWorkPlat(String str,String patten){
        if(str == null) str =  "";
        String[] strs = str.split(patten);
        HashSet set =new HashSet<>();
        Arrays.stream(strs).forEach(itemDistinct ->{
            set.add(this.obtainWorkPlatForm(itemDistinct));
        });
        return (String) set.stream().collect(Collectors.joining(",","",""));
    }

    /**
     * 工单工作平台转化
     * @param str
     * @return
     */
    public String obtainWorkPlatForm(String str){
        String re = "其他";
        if("cosmetology".equals(str)){
            re = "美容";
        }else if("machineRepa".equals(str)){
            re = "机修";
        }else if("sprayPaint".equals(str)){
            re = "钣喷";
        }
        return re;
    }



    public void testCombine(SimpleRequest req){
        JSONObject jo = req.getJO();

        VehicleInfo vehi = repository.findOne(jo.getString("id"));

        listenVehicleInfo(vehi);
    }
}
